<template>
  <div class="cc-login-form">
    <div>
      <q-form @submit="submit" class="q-pa-md bg-white">
        <q-tabs v-model="tab" active-color="primary" indicator-color="primary" align="left" :breakpoint="0" narrow-indicator class="text-black">
          <q-tab name="mails" label="用户密码登录" />
        </q-tabs>
        <div class="q-gutter-y-sm">
          <q-tab-panels v-model="tab" class="text-center">
            <q-tab-panel name="mails" class="q-col-gutter-y-sm">
              <div class="row">
                <div class="col">
                  <q-input outlined clear-icon="cancel" v-model.trim="form.username" debounce="500" lazy-rules square :rules="[
                    (val) => (val && val.length > 0) || '请输入用户名'
                  ]">
                    <template #prepend>
                      <q-icon name="mdi-account-tie" />
                    </template>
                  </q-input>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <q-input outlined clear-icon="cancel" :type="isPwd ? 'password' : 'text'" v-model.trim="form.password" debounce="500" lazy-rules square
                    :rules="[(val) => (val && val.length > 0) || '请输入密码']">
                    <template v-slot:prepend>
                      <q-icon name="lock" />
                    </template>
                    <template v-slot:append>
                      <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isPwd = !isPwd" />
                    </template>
                  </q-input>
                </div>
              </div>
              <div class="row">
                <div style=float:left><q-checkbox v-model="checked" />记住密码 </div>
                <div style=float:right class="forget-the-password" @click="forget">忘记密码</div>
              </div>

            </q-tab-panel>

          </q-tab-panels>

          <div class="q-mx-md">
            <div class="row">
              <div class="col">
                <q-btn dense unelevated label="登 录" size="20px" color="primary q-mt-sm" class="full-width no-border-radius" type="submit" :loading="loading">
                  <template v-slot:loading>
                    <q-spinner-ios class="on-left" />登录...
                  </template>
                </q-btn>
              </div>
            </div>
            <div class="row justify-center q-pt-lg"></div>
          </div>
        </div>
      </q-form>
    </div>
    <cc-dialog ref="dialog" title="信息验证" :hasSubmit="false">
      <div class="q-pa-md col-12">
        <q-stepper class="col-12" v-model="step" ref="stepper" alternative-labels color="primary" animated>
          <q-step class="col-12" :name="1" title="信息验证" icon="settings" :done="step > 1">
            <q-form @submit="changePassword" class="'dialog_card column'">
              <div class="col-12">
                <h5><q-icon name="star" color="red" />用户名：</h5>
                <q-input outlined dense v-model="form.realname" type="text" clearable :rules="[(val) => (val && val.length > 0) || '请输入名称']" />
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />身份证号：</h5>
                <q-input outlined dense v-model="form.idCard" type="text" clearable :rules="[(val) => (val && val.length > 0) || '请输入身份证号']" />
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />手机号：</h5>
                <q-input outlined dense v-model="form.phone" type="text" clearable :rules="[(val) => (val && val.length > 0) || '请输入手机号']" />
              </div>
              <q-stepper-navigation>
                <q-btn type="submit" color="primary" label='验证' />
              </q-stepper-navigation>
            </q-form>

          </q-step>

          <q-step :name="2" title="修改密码" icon="create_new_folder" :done="step > 2">
            <q-form @submit="editPassword" class="'dialog_card column'">
              <div class="col-12">
                <h5>用户名：</h5>
                <q-input outlined readonly dense v-model="form.realname" :rules="[v => !!v || '不可以为空']" />
              </div>
              <div class="col-12">
                <h5>
                  <q-icon name="star" color="red" />密码：
                </h5>
                <q-input outlined dense :type="isEditPwd ? 'password' : 'text'" v-model="form.password" :rules="rules">
                  <template v-slot:append>
                    <q-icon :name="isEditPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isEditPwd = !isEditPwd" />
                  </template>
                </q-input>
              </div>
              <div class="col-12">
                <h5>
                  <q-icon name="star" color="red" />确认密码：
                </h5>
                <q-input outlined dense :type="isEditPwd ? 'password' : 'text'" v-model="form.confirmpassword" :rules="rules">
                  <template v-slot:append>
                    <q-icon :name="isEditPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isEditPwd = !isEditPwd" />
                  </template>
                </q-input>
              </div>
              <q-stepper-navigation>
                <q-btn type="submit" color="primary" label='修改' />
                <!-- <q-btn flat color="primary" @click="$refs.stepper.previous()" label="退回" class="q-ml-sm" /> -->
              </q-stepper-navigation>
            </q-form>
          </q-step>

          <q-step :name="3" title="修改成功" icon="add_comment">
            <q-img src="img/login/achieve.png" :ratio="15 / 6" />
          </q-step>
        </q-stepper>
      </div>

    </cc-dialog>
    <change-password :username="form.username" ref="changePassWord" />
  </div>
</template>

<script>
import { requiredTest } from 'boot/inputTest';
import ChangePassword from 'components/sys/change-password.vue';

export default {
  name: 'Login',
  components: { ChangePassword },
  data() {
    return {
      step: 1,
      title: process.env.PRODUCT_NAME,
      rules: [requiredTest],
      form: {
        username: '',
        password: '',
      },
      tab: 'mails',
      isPwd: true,
      isEditPwd: true,
      autoLogin: true,
      loading: false,
      checked: false,
    };
  },
  methods: {
    changePassword() {
      this.$axios.post('/sys/basicInformation', this.form).then((result) => {
        if (result.code === 200) {
          this.$refs.stepper.next();
          this.updPsw();
        }
        this.form.id = result.result.id;
      }).finally(() => {
      });
    },
    updPsw() {
      this.rules = [requiredTest];
      this.$axios.get(`/sys/company/getTenantInfo?username=${this.form.phone}`).then(({ result }) => {
        const {
          pswMsg, minLength, maxLength, pswStrength
        } = result;
        if (!minLength || !maxLength) {
          this.$error('请管理员设置，密码最大和最小长度');
          return;
        }
        this.rules.push((val) => {
          let t = null;
          if (val.length < parseInt(minLength, 10) || val.length > parseInt(maxLength, 10)) {
            t = `要求密码长度为[${minLength} - ${maxLength}] 个字符`;
          }
          return t;
        });
        if (pswStrength && pswMsg) {
          this.rules.push((val) => {
            let t = null;
            const p = new RegExp(pswStrength, 'g');
            if (val && !p.test(val)) {
              t = pswMsg;
            }
            return t;
          });
        }
      });
    },
    editPassword() {
      if (this.form.password !== this.form.confirmpassword) {
        this.$error('两次输入密码不一致！');
        return;
      }
      this.$axios.put('/sys/user/passwordByUser', {
        id: this.form.id,
        confirmpassword: this.form.confirmpassword,
        password: this.form.password,
        username: this.form.phone,
      }).then((r) => {
        this.$refs.stepper.next();
        this.form.password = '';
      });
    },
    forget() {
      this.$refs.dialog.show();
      this.step = 1;
      this.form = {
        realname: '',
        idCard: '',
        phone: '',
        password: '',
        confirmpassword: ''
      };
    },
    getDefault() {
      if (this.$q.platform.is.mobile) {
        return '/phone/home';
      }
      return '/sub-system';
    },
    submit() {
      this.loading = true;
      this.$axios.post('/sys/login', this.form)
        .then((r) => {
          // 用来记录是否登录
          localStorage.landing = 1;
          localStorage.shipTypeCode = r.result.userInfo.shipType;
          localStorage.shipTypeName = r.result.userInfo.shipTypeName;
          if (this.checked) {
            localStorage.setItem('username', this.form.username);
            localStorage.setItem('password', this.form.password);
          } else {
            localStorage.removeItem('username');
            localStorage.removeItem('password');
          }
          this.$store.commit('Rule/clear');
          this.$store.commit('User/updateAuthorization', r.result.token);
          this.$store.commit('User/updateInfo', r.result.userInfo);
          this.$router.push(this.getDefault());
        }).catch(({ data }) => {
          if (data.code === 40311) {
            // 这里做修改密码
            this.$refs.changePassWord.show();
          }
        }).finally(() => {
          this.loading = false;
        });
    },
  },
  mounted() {
    const username = localStorage.getItem('username');
    if (username) {
      this.form.username = localStorage.getItem('username');
      this.form.password = localStorage.getItem('password');// base64解密
      this.checked = true;
    }
    if (this.$store.state.User.authorization) {
      window.location.replace('#/login');
    } else {
      this.$store.commit('User/clear');
    }
  },
  computed: {
  },
};
</script>

<style scoped>
.forget-the-password {
  color: blue;
  float: left;
  cursor: pointer;
  margin-right: 0px;
  margin-left: 0px;
  margin-top: 8px;
  margin-left: auto;

}
</style>
